﻿using MixerReport.ViewModels;
using hyjx.bind;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using DocumentFormat.OpenXml.Bibliography;
using MixerReport.Objects;
using hyjx.file.Exceptions;

namespace MixerReport.Commands
{
    public class ExportCommand : CommandBase
    {
        public override bool CanExecute(object? parameter)
        {
            if(parameter is not ReportPageViewModel vm)
                return false;

            if(vm.Reports.Count == 0) return false;

            return true;
        }

        public async override void Execute(object? parameter)
        {
            if (!CanExecute(parameter)) return;
            if (parameter is not ReportPageViewModel vm)
                return;

            if (vm.Reports.Count == 0)
            {
                MessageBox.Show("当前没有查询结果，无法导出。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // 弹出文件保存窗口
            SaveFileDialog saveFileDialog = new()
            {
                Filter = "文本文件|*.csv",
                InitialDirectory = "D:\\", //设置初始目录

                FileName = $"{vm.Filter.SelectedMixerName.Value}_{vm.Filter.StartDate?.Year}_{vm.Filter.StartDate?.Month:D2}_{vm.Filter.StartDate?.Day:D2}.csv"
            };

            bool? showResult = saveFileDialog.ShowDialog();
            if (showResult == null || showResult.Value == false)
                return;

            try
            {
                //if (File.Exists(saveFileDialog.FileName))
                //    File.Delete(saveFileDialog.FileName);

                int total = 0; // 导出总行数

                vm.IsExporting = Visibility.Visible;

                await Task.Run(() =>
                {
                    try
                    {
                        // 获取要导出的数据
                        var query = vm.GetAllReports();
                        if (query == null)
                        {
                            MessageBox.Show("获取导出数据出错，导出失败。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }

                        total = query.Count();
                        if (total == 0)
                        {
                            MessageBox.Show("获取导出数据出错，导出失败。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }

                        hyjx.file.CsvHelper csv = new(saveFileDialog.FileName);
                        csv.AppendRow(new string[] { "设备", "记录时间", "当前工步号", "原料", "工步设定时间（分钟）", "工步剩余时间（分钟）", "工步搅拌设定转速（rpm）", "搅拌实际转速（rpm）", "工步分散设定转速（rpm）", "分散实际转速（rpm）", "工步温度设定值", "实际温度（℃）", "工步压力设定值（Kpa）", "实际压力（Kpa）", "工步材料设定重量（KG）", "实际加料量（KG）", "工步搅拌电流", "工步分散电流" });

                        query.ToList().ForEach(p =>
                        {
                            var data = new string[] { p.DeviceName, $" {p.RecordTime}", p.Step.ToString(), p.Material, p.ElapsedTime.ToString(), p.RemainTime.ToString(), p.StirRotateSpeed.ToString(), p.StirRotateActualSpeed.ToString("f3"), p.ScatteredRotateSpeed.ToString(), p.ScatteredRotateActualSpeed.ToString("f3"), p.Temperature.ToString("f3"), p.ActualTemperature.ToString("f3"), p.Pressure.ToString("f3"), p.ActualPressure.ToString("f3"), p.MaterialWeight.ToString("f3"), p.MaterialActualWeight.ToString("f3"), p.StirCurrent.ToString("f3"), p.ScatteredCurrent.ToString("f3") };
                            csv.AppendRow(data);
                        });
                        csv.Save();

                        MessageBox.Show($"成功导出 {total} 条数据记录", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    catch(AppendRowException ex)
                    {

                    }
                });

            }
            catch (Exception ex)
            {
                string error = $"出现异常，导出失败：{ex.Message}";
                MessageBox.Show(error, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                vm.IsExporting = Visibility.Collapsed;
            }
        }
    }
}
